<template>
  <div class="row">
    <el-descriptions
      title="登录帐号"
      label-align="center"
      :column="1"
      border
      class="f-2"
    >
      <el-descriptions-item
        label="用户名"
        label-class-name="my-label"
        label-align="center"
        class-name=""
        align="center"
      >
        <div class="row">
          <span class="f-3">
            {{ user.name }}
          </span>

          <div class="f-1 row jcc">
            <!-- <el-link type="primary"
              ><el-icon class="mr-0-5"><Edit /></el-icon>修改</el-link
            > -->
          </div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="手机" align="center">
        <div class="row">
          <span class="f-3">
            {{ $privacyMobile(user.mobileNumber) }}
          </span>
          <div class="f-1 row jcc">
            <el-link
              type="primary"
              v-if="user.mobileNumber"
              @click="onUpdateMobile()"
              ><el-icon class="mr-0-5"><Edit /></el-icon>修改</el-link
            >
            <el-link v-else type="primary" @click="onAddMobile()"
              ><el-icon class="mr-0-5"><Edit /></el-icon>添加</el-link
            >
          </div>
        </div></el-descriptions-item
      >
      <el-descriptions-item label="密码" align="center">
        <div class="row">
          <span class="f-3"> ****** </span>

          <div class="f-1 row jcc">
            <el-link type="primary" @click="onChangePassword()"
              ><el-icon class="mr-0-5"><Edit /></el-icon>修改</el-link
            >
          </div>
        </div>
      </el-descriptions-item>

      <!-- <el-descriptions-item label="Address" label-align="center" align="center"
        >
        No.1188, Wuzhong Avenue, Wuzhong District, Suzhou, Jiangsu
        Province
        </el-descriptions-item
      > -->
    </el-descriptions>
    <div class="f-1 row jcfe m-2">
      <el-avatar
        :size="150"
        src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
      />
    </div>

    <!-- #region 添加/修改手机号 -->
    <el-dialog
      v-model="updateMobileDialogVisible"
      :title="dialogTitle"
      width="38%"
    >
      <el-form
        ref="updateMobileFormRef"
        label-width="4rem"
        label-position="top"
        :model="updateMobileForm"
        class="mt-1"
        :rules="rules"
      >
        <el-form-item label="手机号" prop="mobileNumber">
          <el-input v-model="updateMobileForm.mobileNumber"></el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="smsvcode">
          <el-input v-model="updateMobileForm.smsvcode">
            <template #append>
              <SendSmsvcodeButton
                :mobileNumber="updateMobileForm.mobileNumber"
              ></SendSmsvcodeButton>
            </template>
          </el-input>
        </el-form-item>
        <div style="text-align: right">
          <el-button type="primary" @click="updateMobileSubmite()"
            >提交</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <!-- #endregion -->

    <!-- #region 账号安全验证 -->
    <el-dialog
      v-model="securityVerificationDialogVisible"
      title="账号安全验证"
      width="38%"
    >
      <h4 class="mt-0">你正在进行敏感操作，继续操作前请验证您的身份</h4>
      <el-tag type="warning" class="w100 p-1" v-if="effectText">{{
        effectText
      }}</el-tag>
      <el-form
        ref="securityVerificationFormRef"
        label-width="4rem"
        label-position="top"
        :model="securityVerificationForm"
        class="mt-1"
        :rules="rules"
      >
        <el-form-item label="密码验证" prop="password">
          <el-input
            v-model="securityVerificationForm.password"
            show-password
            type="password"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="securityVerificationForm.mobileNumber"
          :label="`短信验证(接收手机号 ${$privacyMobile(
            securityVerificationForm.mobileNumber
          )})`"
          prop="smsvcode"
        >
          <el-input v-model="securityVerificationForm.smsvcode">
            <template #append>
              <SendSmsvcodeButton
                :mobileNumber="securityVerificationForm.mobileNumber"
              ></SendSmsvcodeButton>
            </template>
          </el-input>
        </el-form-item>
        <div style="text-align: right">
          <el-button type="primary" @click="onSecurityVerificaNext()"
            >下一步</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <!-- #endregion -->

    <!-- #region 修改密码 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      title="修改密码"
      width="30%"
    >
      <el-form
        ref="passwordFormRef"
        label-width="100px"
        label-position="left"
        :rules="rules"
        :model="changePasswordForm"
      >
        <el-form-item label="新密码：" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            show-password
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmPassword" :rules="rule">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            show-password
            type="password"
          ></el-input>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="ChangePassword(passwordFormRef)"
            >确认修改</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>

<script lang="ts" setup>
import { shios } from '@/api/Shios';
import { rules } from '@/libs/Rules';
import router from '@/route';
import { store } from '@/store';
import { useStoreRef } from '@/store/useStoreRef';
import { ElMessage, FormInstance } from 'element-plus';
import { Ref, reactive, ref } from 'vue';
const user = store.user.state;
const dialogTitle = ref('');
// #region 账号安全验证

const effectText = ref('');
const securityVerificationFormRef = ref<FormInstance>();
const smsvcodeFormRef = ref<FormInstance>();
const securityVerificationDialogVisible = ref(false);
const securityVerificationForm = reactive({
  password: '',
  mobileNumber: user.mobileNumber,
  smsvcode: '',
});
let nextDialogVisible: Ref<boolean> | undefined = undefined;
async function onSecurityVerificaNext() {
  await securityVerificationFormRef.value?.validate();
  const res = await shios.post('user/verifypassword', {
    search: { password: securityVerificationForm.password },
  });
  if (!res.ok) {
    return;
  }
  if (securityVerificationForm.mobileNumber) {
    const res2 = await shios.post('sms/verifycode', {
      data: securityVerificationForm,
    });
    if (!res2.ok) {
      return;
    }
  }
  securityVerificationDialogVisible.value = false;
  if (nextDialogVisible) {
    nextDialogVisible.value = true;
  }
}

// #endregion

// #region 更新手机号
const updateMobileDialogVisible = ref(false);
const updateMobileFormRef = ref<FormInstance>();
const updateMobileForm = reactive({
  password: '',
  mobileNumber: '',
  smsvcode: '',
});
/**
 * 添加手机号
 */
function onAddMobile() {
  effectText.value =
    '添加号码后，你将可以通过 「手机号码+短信验证码」 登录、密码找回';
  dialogTitle.value = '添加手机号';
  securityVerificationDialogVisible.value = true;
  nextDialogVisible = updateMobileDialogVisible;
}
/**
 * 修改手机号
 */
function onUpdateMobile() {
  effectText.value = '修改号码后，你将无法通过 「原手机号码+短信验证码」 登录';
  dialogTitle.value = '修改手机号';
  securityVerificationDialogVisible.value = true;
  securityVerificationForm.mobileNumber = user.mobileNumber;
  nextDialogVisible = updateMobileDialogVisible;
}
async function updateMobileSubmite() {
  await updateMobileFormRef.value?.validate();
  updateMobileForm.password = securityVerificationForm.password;
  const res = await shios.patch('user/UpdateMobile', {
    data: updateMobileForm,
  });
  if (res.ok) {
    ElMessage.success(dialogTitle.value + '成功');
    updateMobileDialogVisible.value = false;
    user.mobileNumber = updateMobileForm.mobileNumber;
    store.user.update(user);
  }
}
// #endregion

// #region 修改密码
function onChangePassword() {
  effectText.value = '修改密码后，你将无法通过 「原密码」 登录';
  securityVerificationDialogVisible.value = true;
  securityVerificationForm.mobileNumber = '';
  nextDialogVisible = changePasswordDialogVisible;
}
function confirmPassword(rule: any, value: any, callback: any) {
  return value == changePasswordForm.newPassword
    ? callback()
    : callback(new Error('密码不一致'));
}
const rule = {
  validator: confirmPassword,
  trigger: 'blur',
};
const changePasswordDialogVisible = ref(false);
const passwordFormRef = ref<FormInstance>();

const changePasswordForm = reactive({
  password: '',
  newPassword: '',
  confirmPassword: '',
});
/** 修改密码 */
async function ChangePassword(formEl: FormInstance | undefined) {
  if (!formEl) return;
  await formEl.validate();
  changePasswordForm.password = securityVerificationForm.password;
  const res = await shios.patch('User/ChangePassword', {
    data: changePasswordForm,
  });
  if (res.ok) {
    localStorage.setItem('remember-user', JSON.stringify({ name: user?.name }));
    router.replace('/login');
    ElMessage.success('修改成功,请重新登录');
  }
}

// #endregion
</script>

<style lang="scss" scoped>
:deep(.my-label) {
  background: var(--el-color-success-light-9) !important;
}
:deep(.my-content) {
  background: var(--el-color-danger-light-9);
}
:deep(.my-content) {
  width: 20px;
}
</style>
